<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

try {

    $db = new DB();
    $pdo = $db::$pdo;

    $article_id = trim($_SERVER['PATH_INFO'], '/');

    if (!isset($article_id)) {
        throw new Exception(fieldMap('article_id') . '为必传项');
    }

    if (empty($article_id)) {
        throw new Exception(fieldMap('article_id') . '不能为空');
    }

    // 查询文章是否存在
    $sql = 'select * from articles where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$article_id]);
    if (empty($stmt->fetch(PDO::FETCH_ASSOC))) {
        throw new Exception('文章不存在，无法获取评论');
    }

    // 查询评论
    $sql = 'select * from comments where article_id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$article_id]);
    $commentRes = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 查询用户
    $sql = 'select * from users where id = ?';
    $stmt = $pdo->prepare($sql);
    foreach ($commentRes as &$value) {
        $stmt->execute([$value['user_id']]);
        $userRes = $stmt->fetch(PDO::FETCH_ASSOC);
        $value['user'] = $userRes;
        unset($value);
    }

    myResponse('', 1, 200, $commentRes);
} catch (Exception $e) {
    myResponse($e->getMessage(), 0, 200);
}